

package Principal;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.mxrck.autocompleter.TextAutoCompleter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import static javax.swing.JFileChooser.SAVE_DIALOG;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import preparedstatement.DebugLevel;
import preparedstatement.StatementFactory;

/**
 * Clase para la localizacion e ingreso de clientes para facutrar. Impresion y
 * envio de factura.
 *
 * @author Pascual Guerrero
 * @author Enrique Perera
 * @version "1.0.0, 01/07/13"
 * @since Principal 1.0.0
 */
public final class facturacion extends javax.swing.JFrame {

    // Inicializar datos
    TextAutoCompleter textAutoCompleter;
    DefaultTableModel dtm;
    local_connection conexion;
    Connection cn;
    PreparedStatement ps;
    ResultSet rs;
    int code;
    int idpersona = 0;
    NumberFormat formatter;
    int folio;
    String formadepago;
    java.text.SimpleDateFormat sdf2 = new java.text.SimpleDateFormat("dd-MM-yyyy");
    String asunto, mensaje;

    /**
     * Metodo que conecta a la base de datos .
     *
     * @param cd
     * @since Principal 1.0.0
     */
    public facturacion(int cd) {
        initComponents();
        pago.setSelected(efectivo.getModel(), true);
        formatter = NumberFormat.getCurrencyInstance();
        code = cd;
        textAutoCompleter = new TextAutoCompleter(cliente);
        textAutoCompleter.setMode(0);
        textAutoCompleter.setCaseSensitive(false);
        sologuardar.setSelected(true);
        try {
            cn = local_connection.getconnect();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        cargarDatos();
        asunto = "TeslaBEM. Factura-" + folio + "-" + sdf2.format(fecha.getDate());
        mensaje = "Adjunto la factura correspondiente a la compra con folio " + folio;
    }

    /**
     * Metodo para cargar los datos de los clientes
     *
     */
    void cargarDatos() {
        int pesoo = 0;
        int cantidad = 0;
        float total = 0;
        try {
            ps = (PreparedStatement) cn.prepareStatement("Select factura from numeros");
            rs = ps.executeQuery();
            rs.next();
            folio = rs.getInt(1);
            fecha.setDate(new Date());
            dtm = (DefaultTableModel) this.jTable1.getModel();
            dtm.setRowCount(0);
            ArrayList<Object[]> data = new ArrayList<>();
            Object[] rows = new Object[jTable1.getColumnCount()];
            ps = (PreparedStatement) cn.prepareStatement("select nombre, paterno, materno from personas");
            rs = ps.executeQuery();
            while (rs.next()) {
                textAutoCompleter.addItem(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3));
            }
            ps = (PreparedStatement) cn.prepareStatement("select ticket, fecha from venta where folio = " + code);
            rs = ps.executeQuery();
            rs.next();
            folioventa.setText(String.valueOf(code));
            ticket.setText(rs.getString("ticket"));
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            fventa.setText(dateFormat.format(rs.getDate("fecha")));
            ps = (PreparedStatement) cn.prepareStatement("Select detalleventa.id_producto,productos.nombre, sum(productos.peso*cantidad), sum(preciovendido*cantidad), cantidad, preciovendido from detalleventa join productos on detalleventa.id_producto = productos.id_producto where folio =  ? group by idetalle");
            ps.setInt(1, code);
            rs = ps.executeQuery();

            while (rs.next()) {
                total += rs.getFloat("sum(preciovendido*cantidad)");
                pesoo += rs.getInt("sum(productos.peso*cantidad)");
                cantidad += rs.getInt("cantidad");
                rows[0] = rs.getString("id_producto");
                rows[1] = rs.getInt("cantidad");
                rows[2] = rs.getString("productos.nombre");
                rows[3] = rs.getString("preciovendido");
                rows[4] = rs.getFloat("sum(preciovendido*cantidad)");
                data.add(rows);
                dtm.addRow(data.get(0));
            }

            peso.setText(String.valueOf(pesoo));
            clineas.setText(String.valueOf(jTable1.getRowCount()));
            cproductos.setText(String.valueOf(cantidad));
            importetotal.setText(formatter.format(total));
            subtotal.setText(formatter.format(total * .84));
            iva.setText(formatter.format(total * .16));
            iva.setEditable(false);
            subtotal.setEditable(false);
            importetotal.setEditable(false);
            cliente.requestFocus();
            data.clear();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pago = new javax.swing.ButtonGroup();
        guardar = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        folioventa = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        ticket = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        foliofac = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        fventa = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        cliente = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        rfc = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        calle = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        interior = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        exterior = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        colonia = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        ciudad = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        cp = new javax.swing.JTextField();
        jLabel17 = new javax.swing.JLabel();
        estado = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        efectivo = new javax.swing.JRadioButton();
        cheque = new javax.swing.JRadioButton();
        transferencia = new javax.swing.JRadioButton();
        jLabel28 = new javax.swing.JLabel();
        Email = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        sologuardar = new javax.swing.JRadioButton();
        jLabel27 = new javax.swing.JLabel();
        personalizar = new javax.swing.JButton();
        Cancelar = new javax.swing.JButton();
        fecha = new com.toedter.calendar.JDateChooser();
        enviarcorreo = new javax.swing.JRadioButton();
        jButton3 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel20 = new javax.swing.JLabel();
        subtotal = new javax.swing.JFormattedTextField();
        cproductos = new javax.swing.JLabel();
        jLabel24 = new javax.swing.JLabel();
        jLabel26 = new javax.swing.JLabel();
        jLabel22 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        importetotal = new javax.swing.JFormattedTextField();
        jLabel25 = new javax.swing.JLabel();
        peso = new javax.swing.JLabel();
        iva = new javax.swing.JFormattedTextField();
        clineas = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconImage(new ImageIcon(getClass().getResource("/Imagenes/logo_rayito.png")).getImage());
        setResizable(false);

        jLabel1.setText("Folio Venta:");

        folioventa.setText("-----");

        jLabel3.setText("Ticket:");

        ticket.setText("-----");

        jLabel5.setText("Folio Factura:");

        foliofac.setText("-----");

        jLabel7.setText("Fecha venta:");

        fventa.setText("------");

        jLabel9.setText("Cliente:");

        cliente.setNextFocusableComponent(Email);
        cliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clienteActionPerformed(evt);
            }
        });
        cliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                clienteKeyReleased(evt);
            }
        });

        jLabel10.setText("RFC:");

        rfc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rfcActionPerformed(evt);
            }
        });

        jLabel11.setText("Calle:");

        jLabel12.setText("# Int:");

        jLabel13.setText("#Ext:");

        jLabel14.setText("Colonia:");

        jLabel15.setText("Ciudad:");

        jLabel16.setText("CP:");

        jLabel17.setText("Estado:");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Cantidad", "Nombre", "P.Unit.", "Importe"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        pago.add(efectivo);
        efectivo.setText("Efectivo");
        efectivo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                efectivoActionPerformed(evt);
            }
        });

        pago.add(cheque);
        cheque.setText("Cheque");

        pago.add(transferencia);
        transferencia.setText("Transferencia");

        jLabel28.setText("Email:");

        Email.setNextFocusableComponent(rfc);

        guardar.add(sologuardar);
        sologuardar.setText("Solo guardar");

        jLabel27.setText("Fecha:");

        personalizar.setText("Personalizar Mensaje");
        personalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                personalizarActionPerformed(evt);
            }
        });

        Cancelar.setText("Cancelar");
        Cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelarActionPerformed(evt);
            }
        });

        guardar.add(enviarcorreo);
        enviarcorreo.setText("Guardar Y Enviar");

        jButton3.setText("Aceptar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel27)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(fecha, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(sologuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(enviarcorreo)
                        .addGap(16, 16, 16)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(personalizar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(Cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(Cancelar)
                            .addComponent(jButton3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(personalizar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(enviarcorreo)
                            .addComponent(sologuardar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel27, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(fecha, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );

        jLabel20.setText("Productos:");

        subtotal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getCurrencyInstance())));

        cproductos.setText("------");

        jLabel24.setText("Subtotal:");

        jLabel26.setText("IVA:");

        jLabel22.setText("Peso Total(GR)");

        jLabel18.setText("En Lista:");

        importetotal.setBackground(new java.awt.Color(0, 0, 0));
        importetotal.setForeground(new java.awt.Color(255, 255, 255));
        importetotal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getCurrencyInstance())));
        importetotal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        importetotal.setCaretColor(new java.awt.Color(255, 255, 255));
        importetotal.setFont(new java.awt.Font("Tahoma", 1, 22)); // NOI18N
        importetotal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importetotalActionPerformed(evt);
            }
        });

        jLabel25.setText("Importe Total:");

        peso.setText("-------");

        iva.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getCurrencyInstance())));

        clineas.setText("------");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel26)
                                .addGap(27, 27, 27)
                                .addComponent(iva))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel24)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(subtotal))
                            .addComponent(jLabel25)
                            .addComponent(importetotal, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addComponent(clineas)
                                .addGap(23, 23, 23))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel18)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel20)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(cproductos)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(peso))
                            .addComponent(jLabel22))))
                .addGap(0, 0, 0))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel20)
                    .addComponent(jLabel22)
                    .addComponent(jLabel18))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(clineas)
                    .addComponent(cproductos)
                    .addComponent(peso))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel24)
                    .addComponent(subtotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel26)
                    .addComponent(iva, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel25)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(importetotal, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(folioventa)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ticket)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(foliofac)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(fventa)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel28)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(Email, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel15)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(ciudad, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel16)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(cp, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel11)
                                            .addComponent(jLabel9))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addGroup(layout.createSequentialGroup()
                                                .addComponent(calle, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(jLabel12)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(interior, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(jLabel13)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(exterior, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addComponent(cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 277, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel10)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(rfc))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel14)
                                            .addComponent(jLabel17))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(colonia)
                                            .addComponent(estado, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(transferencia)
                                    .addComponent(efectivo)
                                    .addComponent(cheque))))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 402, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(folioventa)
                    .addComponent(jLabel3)
                    .addComponent(ticket)
                    .addComponent(jLabel5)
                    .addComponent(foliofac)
                    .addComponent(jLabel7)
                    .addComponent(fventa)
                    .addComponent(jLabel28)
                    .addComponent(Email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10)
                    .addComponent(rfc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(efectivo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(calle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12)
                    .addComponent(interior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13)
                    .addComponent(exterior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel14)
                    .addComponent(colonia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cheque))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(ciudad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel16)
                    .addComponent(cp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel17)
                    .addComponent(estado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(transferencia))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void clienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clienteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_clienteActionPerformed

    private void rfcActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rfcActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_rfcActionPerformed

    private void importetotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importetotalActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_importetotalActionPerformed

    private void efectivoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_efectivoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_efectivoActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        if (Email.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Tiene que ingresar un correo electronico para enviar la factura");
        } else if (!cliente.getText().equals("") && !rfc.getText().equals("")) {
            try {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                String nombre = (VentanaPrincipal.local)?"nombre||' '||paterno||' '||materno":"concat(nombre,' ',paterno,' ',materno)";
                ps = (PreparedStatement) cn.prepareStatement("select id_persona from personas where "+nombre+" = ?");
                //ps.setString(1, rfc.getText());
                ps.setString(1, cliente.getText());
                rs = ps.executeQuery();
                if (rs.next()) {
                    idpersona = rs.getInt(1);
                    ps = StatementFactory.getStatement(local_connection.cn,"Update personas set email = ?, calle = ?, numero_interior = ?, numero_exterior = ?, colonia = ?, ciudad = ?, cp = ?, estado = ? where id_persona = " + idpersona,DebugLevel.ON);

                    ps.setString(1, Email.getText());
                    ps.setString(2, calle.getText());
                    ps.setString(3, interior.getText());
                    ps.setString(4, exterior.getText());
                    ps.setString(5, colonia.getText());
                    ps.setString(6, ciudad.getText());
                    ps.setString(7, cp.getText());
                    ps.setString(8, estado.getText());
                    ps.execute();
                    VentanaPrincipal.guardarCache(ps, "personas", true);
                } else {
                    ps = StatementFactory.getStatement(local_connection.cn,"insert into personas(nombre, email, calle, numero_interior, numero_exterior, colonia, ciudad, cp, estado,rfc,paterno,materno) values(?,?,?,?,?,?,?,?,?,?,'','')",DebugLevel.ON);
                    ps.setString(1, cliente.getText());
                    ps.setString(2, Email.getText());
                    ps.setString(3, calle.getText());
                    ps.setString(4, interior.getText());
                    ps.setString(5, exterior.getText());
                    ps.setString(6, colonia.getText());
                    ps.setString(7, ciudad.getText());
                    ps.setString(8, cp.getText());
                    ps.setString(9, estado.getText());
                    ps.setString(10, rfc.getText());
                    ps.execute();
                    VentanaPrincipal.guardarCache(ps, "personas", true);
                    String last=(VentanaPrincipal.local)?"last_insert_rowid":"LAST_INSERT_ID";
                    ps=cn.prepareStatement("Select "+last+"()");
                    rs=ps.executeQuery();
                    idpersona = rs.getInt(1);
                }
                if (efectivo.isSelected()) {
                    formadepago = "Efectivo";
                }
                if (cheque.isSelected()) {
                    formadepago = "Cheque";
                }
                if (transferencia.isSelected()) {
                    formadepago = "Transferencia";
                }
                ps = StatementFactory.getStatement(local_connection.cn,"update venta set id_cliente = ? where folio = ?",DebugLevel.ON);
                ps.setInt(1, idpersona);
                ps.setInt(2, code);
                ps.execute();
                VentanaPrincipal.guardarCache(ps, "venta", true);
                ps = StatementFactory.getStatement(local_connection.cn,"Insert into factura (id_ventap, fecha, pago) values(?,?,?)",DebugLevel.ON);
                ps.setInt(1, code);
                ps.setString(2, sdf.format(fecha.getDate()));
                ps.setString(3, formadepago);
                ps.execute();
                VentanaPrincipal.guardarCache(ps, "factura", true);
                if (enviarcorreo.isSelected()) {
                    URL resource = facturacion.class.getResource("/Factura/Factura.jasper");
                    JasperReport reporte = (JasperReport) JRLoader.loadObject(resource);
                    Map<String, Object> parametros = new HashMap<>();
                    parametros.put("Folio", String.valueOf(code));
                    parametros.put("Forma de pago", formadepago);
                    parametros.put("Factura", String.valueOf(folio));
                    parametros.put("Fecha", sdf2.format(fecha.getDate()));
                    JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, cn);
                    JRExporter exporter = new JRPdfExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
                    exporter.setParameter(JRExporterParameter.OUTPUT_FILE, new java.io.File("Facturas/Factura-" + folio + "-" + rfc.getText() + ".pdf"));
                    exporter.exportReport();
                    enviar();
                } else {
                    guardar();
                }
                this.dispose();
            } catch (SQLException | JRException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton3ActionPerformed
    void guardar() {
        File file = null;
        final JFileChooser fileopen = new JFileChooser() {
            @Override
            public void approveSelection() {
                File f = getSelectedFile();
                if (f.exists() && getDialogType() == SAVE_DIALOG) {
                    int result = JOptionPane.showConfirmDialog(this,
                            "Este archivo ya existe, ¿Quieres sobreescribirlo?", "Archivo Existente",
                            JOptionPane.YES_NO_CANCEL_OPTION);
                    switch (result) {
                        case JOptionPane.YES_OPTION:
                            super.approveSelection();
                            return;
                        case JOptionPane.CANCEL_OPTION:
                            cancelSelection();
                            return;
                        default:
                            return;
                    }
                }
                super.approveSelection();
            }
        };
        int ret = fileopen.showSaveDialog(null);
        if (ret == JFileChooser.APPROVE_OPTION) {
            file = new File(fileopen.getSelectedFile() + ".pdf");
        }
        try {


            URL resource = facturacion.class.getResource("/Factura/Factura.jasper");
            JasperReport reporte = (JasperReport) JRLoader.loadObject(resource);
            Map<String, Object> parametros = new HashMap<>();
            parametros.put("Folio", String.valueOf(code));
            parametros.put("Forma de pago", formadepago);
            parametros.put("Factura", String.valueOf(folio));
            parametros.put("Fecha", sdf2.format(fecha.getDate()));
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, cn);
            JRExporter exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            new FileWriter(file);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE, file);
            exporter.exportReport();
            System.gc();
            // TODO add your handling code here:
        } catch (JRException | IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    void enviar() {
        try {
            Properties props = new Properties();

            // Nombre del host de correo, es smtp.gmail.com
            props.setProperty("mail.smtp.host", "smtp.gmail.com");

            // TLS si está disponible
            //props.setProperty("mail.smtp.starttls.enable", true);

            props.put("mail.smtp.starttls.enable", true);
            // Puerto de gmail para envio de correos
            props.setProperty("mail.smtp.port", "587");

            // Nombre del usuario
            props.setProperty("mail.smtp.user", "ventas@teslabem.com");

            // Si requiere o no usuario y password para conectarse.
            //props.setProperty("mail.smtp.auth", true);
            props.put("mail.smtp.auth", true);

            Session session = Session.getDefaultInstance(props);

            // Para obtener un log de salida más extenso
            // session.setDebug(true);


            MimeMessage message = new MimeMessage(session);

            // Quien envia el correo
            message.setFrom(new InternetAddress("ventas@teslabem.com"));

            // A quien va dirigido
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(Email.getText()));

            message.setSubject(asunto);
            message.setText(mensaje);
            BodyPart texto = new MimeBodyPart();

// Texto del mensaje
            texto.setText(mensaje);
            BodyPart adjunto = new MimeBodyPart();

            // Cargamos la imagen
            adjunto.setDataHandler(new DataHandler(new FileDataSource("Facturas/Factura-" + folio + "-" + rfc.getText() + ".pdf")));

            // Opcional. De esta forma transmitimos al receptor el nombre original del
            // fichero de imagen.
            adjunto.setFileName("Factura-" + folio + "-" + rfc.getText() + ".pdf");
            MimeMultipart multiParte = new MimeMultipart();
            multiParte.addBodyPart(texto);
            multiParte.addBodyPart(adjunto);


            // Se mete el texto y la foto adjunta.
            message.setContent(multiParte);
            Transport t = session.getTransport("smtp");

            // Aqui usuario y password de gmail
            t.connect("ventas@teslabem.com", "60JY_X92a");
            t.sendMessage(message, message.getAllRecipients());
            t.close();
        } catch (MessagingException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }

    }
    private void CancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CancelarActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_CancelarActionPerformed

    private void clienteKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_clienteKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            try {
                String nombre = (VentanaPrincipal.local)?"nombre||' '||paterno||' '||materno":"concat(nombre,' ',paterno,' ',materno)";
                ps = (PreparedStatement) cn.prepareStatement("Select id_persona, email, rfc, calle, numero_interior, numero_exterior, colonia, ciudad, cp, estado from personas where "+nombre+"like ?");
                ps.setString(1, cliente.getText());
                //System.out.println("Select email, rfc, calle, numero_interior, numero_exterior, colonia, ciudad, cp, estado,id_persona from personas where concat(nombre,' ',paterno,' ',materno) like '" + cliente.getText() + "'");
                rs = ps.executeQuery();
                if (rs.next()) {
                    rfc.setText(rs.getString("rfc"));
                    Email.setText(rs.getString("email"));
                    calle.setText(rs.getString("calle"));
                    interior.setText(rs.getString("numero_interior"));
                    exterior.setText(rs.getString("numero_exterior"));
                    colonia.setText(rs.getString("colonia"));
                    ciudad.setText(rs.getString("ciudad"));
                    cp.setText(rs.getString("cp"));
                    estado.setText(rs.getString("estado"));
                    idpersona = rs.getInt("id_persona");
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_clienteKeyReleased
    public void personalizarMensaje(String Asunto, String Mensaje) {
        asunto = Asunto;
        mensaje = Mensaje;
    }
    private void personalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_personalizarActionPerformed
        personalizarEmail personalizarmensaje;
        personalizarmensaje = new personalizarEmail(asunto, mensaje, this,Email.getText());
        personalizarmensaje.setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_personalizarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Cancelar;
    private javax.swing.JTextField Email;
    private javax.swing.JTextField calle;
    private javax.swing.JRadioButton cheque;
    private javax.swing.JTextField ciudad;
    private javax.swing.JTextField cliente;
    private javax.swing.JLabel clineas;
    private javax.swing.JTextField colonia;
    private javax.swing.JTextField cp;
    private javax.swing.JLabel cproductos;
    private javax.swing.JRadioButton efectivo;
    private javax.swing.JRadioButton enviarcorreo;
    private javax.swing.JTextField estado;
    private javax.swing.JTextField exterior;
    private com.toedter.calendar.JDateChooser fecha;
    private javax.swing.JLabel foliofac;
    private javax.swing.JLabel folioventa;
    private javax.swing.JLabel fventa;
    private javax.swing.ButtonGroup guardar;
    private javax.swing.JFormattedTextField importetotal;
    private javax.swing.JTextField interior;
    private javax.swing.JFormattedTextField iva;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel26;
    private javax.swing.JLabel jLabel27;
    private javax.swing.JLabel jLabel28;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.ButtonGroup pago;
    private javax.swing.JButton personalizar;
    private javax.swing.JLabel peso;
    private javax.swing.JTextField rfc;
    private javax.swing.JRadioButton sologuardar;
    private javax.swing.JFormattedTextField subtotal;
    private javax.swing.JLabel ticket;
    private javax.swing.JRadioButton transferencia;
    // End of variables declaration//GEN-END:variables
}
